package com.jeesite.modules.filter;

import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.web.http.ServletUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件上传过滤器
 * @author guohusong
 * @version 1.0
 * @date 2022/8/20 14:54
 */
@Component
public class FileUploadFilter implements Filter {
    private static String SUFFIX = "/file/upload";

    private static String[] imageAllowSuffixes = new String[]{".gif",".bmp",".jpeg",".jpg",".ico",".png",".tif",".tiff"};

    private static String[] mediaAllowSuffixes = new String[]{".flv",".swf",".mkv",".webm",".mid",".mov",".mp3",
            ".mp4",".m4v",".mpc",".mpeg",".mpg",".swf",".wav",".wma",".wmv",".avi",".rm",".rmi",".rmvb",".aiff",".asf",".ogg",".ogv"};

    private static String[] fileAllowSuffixes = new String[]{".doc",".docx",".rtf",".xls",".xlsx",".csv",
            ".ppt",".pptx",".pdf",".PDF",".vsd",".txt",".md",".xml",".rar",".zip","7z",".tar",".tgz",".jar",
            ".gz",".gzip",".bz2",".cab",".iso",".ipa",".apk"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith(SUFFIX)){
            String fileName = request.getParameter("fileName");
            String fileMd5 = request.getParameter("fileMd5");
            fileMd5 = EncodeUtils.sqlFilter(fileMd5);
            if(fileName.contains(".")){
                int i = fileName.lastIndexOf(".");
                String fileExt = fileName.substring(i);

                boolean img = ArrayUtils.contains(imageAllowSuffixes, fileExt);
                boolean med = ArrayUtils.contains(mediaAllowSuffixes, fileExt);
                boolean fil = ArrayUtils.contains(fileAllowSuffixes, fileExt);
                if(img || med || fil){
                    filterChain.doFilter(servletRequest,servletResponse);
                }else{
                    ServletUtils.renderResult(response, Global.FALSE, "上传失败");
                }

            }else{
                ServletUtils.renderResult(response, Global.FALSE, "上传失败");
            }

        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
